package com.dingreading.cloud.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.*;

/**
 * 小程序-数据处理工具
 */
public class JsonUtil {

    /**
     * 转JSONObject
     *
     * @param obj obj
     * @return obj
     */
    public static JSONObject toJsonObject(Object obj) {
        JSONObject object = JSONObject.parseObject(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat));
        return object;
    }

    /**
     * 转String
     *
     * @param obj obj
     * @return obj
     */
    public static String toJsonString(Object obj) {
        return JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
    }

    /**
     * 把一个文件中的内容读取成一个String字符串
     */
    public static String jsonFileToStr(File jsonFile){
        String jsonStr = "";
        try {
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
